//
//  LHTextView.swift
//  LHWeiBo
//
//  Created by snowimba on 16/1/27.
//  Copyright © 2016年 snowimba. All rights reserved.
//

import UIKit

@IBDesignable
class LHTextView: UITextView {

	@IBInspectable var placeholder : String? {

		didSet {

			placeholderLbl.text = placeholder
		}
	}

	override var text : String? {

		didSet {

			placeholderLbl.hidden = self.hasText()
		}
	}

	override var font: UIFont? {

		didSet {

			placeholderLbl.font = font
		}
	}

	override init(frame: CGRect, textContainer: NSTextContainer?) {

		super.init(frame: frame, textContainer: textContainer)

		setupUI()
	}

	private func setupUI() {

		addSubview(placeholderLbl)

		NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
	}
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }

	@objc private func textDidChange() {

		placeholderLbl.hidden = self.hasText()
	}

	override func layoutSubviews() {
		super.layoutSubviews()

		placeholderLbl.frame.origin = CGPointMake(5, 8)

		guard let textStr = placeholder else {

			return
		}
		let size = (textStr as NSString).boundingRectWithSize(CGSizeMake(self.frame.width - 2 * placeholderLbl.frame.origin.x - 3, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: placeholderLbl.font], context: nil).size
		placeholderLbl.frame.size = size
	}

	required init?(coder aDecoder: NSCoder) {
		super.init(coder: aDecoder)
		setupUI()
	}

	private lazy var placeholderLbl : UILabel = {

		let lbl = UILabel()
		lbl.font = UIFont.systemFontOfSize(12)
		lbl.textColor = UIColor.lightGrayColor()
		lbl.numberOfLines = 0
		return lbl
	}()

	
}
